
#include "PluginManger.h"
#include <QApplication>
#include <QPluginLoader>
#include <QDir>
#include <QDebug>

PluginManger::PluginManger() {
    loadAllPlugins();
}

void PluginManger::loadAllPlugins() {
    QDir pluginDir = QDir(QApplication::applicationDirPath() + PLUGIN_FOLDER);
    if (!pluginDir.exists()) {
        qDebug() << "Plugin dir not exist:" << pluginDir.absolutePath();
        return;
    }

    m_plugins.clear();
    foreach (const QString& fileName, pluginDir.entryList(QDir::Files)) {
        QString pluginPath = pluginDir.absoluteFilePath(fileName);
        QPluginLoader loader(pluginPath);

        // 1. 先检查插件是否加载成功
        if (!loader.load()) {
            qDebug() << "Load plugin failed:" << fileName << "Error:" << loader.errorString();
            continue;
        }

        // 2. 获取插件的 QObject* 实例
        QObject* obj = loader.instance();
        if (!obj) {
            qDebug() << "Get plugin object failed:" << fileName;
            loader.unload(); // 加载成功但无对象，需卸载
            continue;
        }

        // 3. 关键：先转具体子接口（IDatabasePlugin*），再转基接口（ISourcePlugin*）
        IDatabasePlugin* dbPlugin = qobject_cast<IDatabasePlugin*>(obj);
        if (!dbPlugin) {
            qDebug() << "Plugin is not IDatabasePlugin type:" << fileName;
            loader.unload();
            continue;
        }

        // 4. 再转基接口（此时转换必然成功，因为接口声明已正确）
        PluginObject sourcePlugin = qobject_cast<ISourcePlugin*>(dbPlugin);
        if (!sourcePlugin) {
            qDebug() << "Unexpected error: Can't cast to ISourcePlugin:" << fileName;
            loader.unload();
            continue;
        }

        // 5. 插入到插件Map（后续逻辑保持不变）
        ISourcePlugin::E_Plugin_Name pluginName = sourcePlugin->pluginName();
        ISourcePlugin::E_Plugin_Type pluginType = sourcePlugin->pluginType();
        if (m_plugins[pluginType].contains(pluginName)) {
            qDebug() << "Plugin name duplicated:" << fileName;
            loader.unload();
            continue;
        }

        m_plugins[pluginType].insert(pluginName, sourcePlugin);
        qDebug() << "Load plugin success:" << fileName << "Type:" << pluginType << "Name:" << pluginName;
    }
}


PluginMap PluginManger::getPlugins() {
    return m_plugins;
}

PluginManger & PluginManger::createInstance() {
    static PluginManger instance;
    return instance;
}


